//
//  ViewController.m
//  UItableView
//
//  Created by fly on 15/12/22.
//  Copyright © 2015年 fly. All rights reserved.
//

#import "KindOfCarViewController.h"
#import "AboutCarViewController.h"

@interface KindOfCarViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating>
{
    
    NSMutableArray * _dateSource;//数据源
    
    NSMutableArray * _fonsArray;//字体名称数组
    
    NSMutableDictionary * _infoDic;
    
    NSMutableArray * _array;
    
    NSMutableArray * _resultArray;
}
@property(nonatomic,strong)UITableView * tableView;

@property(nonatomic, strong)UISearchController * searchController;

@property (nonatomic, strong)NSDictionary * dic;

-(void)initializeDataSource;//初始化数据源

-(void)initializeInterface;//初始化界面

@end

@implementation KindOfCarViewController

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -dealloc


#pragma mark - init

-(instancetype)init
{
    self = [super init];
    
    if (self) {
        
        self.navigationItem.title = @"汽车品牌";
        
    }
    return self;
}



#pragma mark- 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializeDataSource];
    
    [self initializeInterface];
    
}



#pragma mark- 初始化数据和界面
-(void)initializeDataSource
{
    _dic =[NSDictionary dictionary];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"aboutCar" ofType:@"plist"];
    _dic = [NSDictionary dictionaryWithContentsOfFile:filePath];

    _infoDic = [NSMutableDictionary dictionary];
    
    for (NSString * fontString in [_dic allKeys]) {
        
        NSMutableString*mutableString=[NSMutableString stringWithString:fontString];
        
        CFStringTransform((CFMutableStringRef)mutableString,NULL, kCFStringTransformToLatin, false);
        
        mutableString=(NSMutableString*)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
        //截取首字母，转化大写
        NSString * fristLetter = [[mutableString substringToIndex:1]uppercaseString];
        
        if ([fristLetter isEqualToString:@"Z"]) {
            fristLetter =@"C";
        }
        
        //取出首字母作为key 对应的value
        NSMutableArray * fonts = [NSMutableArray arrayWithArray:_infoDic[fristLetter]];
        //将去到的fontString 放到数组中
        [fonts addObject:fontString];
        //
        [fonts sortUsingSelector:@selector(caseInsensitiveCompare:)];
        
        [_infoDic setObject:fonts forKey:fristLetter];
        
        _array = [NSMutableArray arrayWithArray:[_infoDic allKeys]];
        
        
        [_array sortUsingSelector:@selector(caseInsensitiveCompare:)];
        
        _resultArray = [[NSMutableArray alloc]init];
    }
    
}

-(void)initializeInterface
{
    
    self.view.backgroundColor=  [UIColor whiteColor];
    
    //加载控件
    [self.view addSubview:self.tableView];
    //加载搜索框
    self.tableView.tableHeaderView = self.searchController.searchBar;
    
    
    
}
#pragma mark-系统协议方法-<UITableViewDataSource>
//一共有多少组（只走一次）
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_searchController.active) {
        return 1;
    }
    
    else{
        return _array.count;
    }
}

//设置每一组有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (_searchController.active) {
        return _resultArray.count;
    }
    
    return [_infoDic[_array[section]]count];
    
    
}
//设置单元行样式
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString * identify = @"Cell";
    
    //    UITableViewCell * cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    //利用重用标示符去重用队列里找
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identify];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identify];
    }
    
       if (_searchController.active) {
        
        cell.textLabel.text = _resultArray[indexPath.row];
    }
    else
    {
        
        cell.textLabel.text = _infoDic[_array[indexPath.section]][indexPath.row];
        
    }
    
    return cell;
    
}
//设置索引栏
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    
    
    return _array;
    
}
//每一组的头部标题
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return  _array[section];
    
}

#pragma mark-系统协议方法-<UITableViewDelegate>
//选中状态下
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AboutCarViewController * VC = [[AboutCarViewController alloc]init];
    
    VC.aboutCar =[_dic objectForKey:_infoDic[_array[indexPath.section]][indexPath.row]];
    
    [[NSUserDefaults standardUserDefaults] setObject:_infoDic[_array[indexPath.section]][indexPath.row] forKey:@"carName"];
    
    
    [self.navigationController pushViewController:VC animated:YES];
    
}
#pragma mark <UISearchResultsUpdating>协议方法
//输入搜索内容改变就会调用该方法
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController;
{
    //获取搜索内容
    NSString * string = searchController.searchBar.text;
    //谓词：用来过滤搜索条件
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH [cd] %@",string];
    //  ENDSWITH 以搜索字符结尾的结果集
    // BEGINSWITH 以搜索字符开头的结果集
    //[cd]不区分大小写
    [_resultArray removeAllObjects];
    
    [_resultArray addObjectsFromArray:[_fonsArray filteredArrayUsingPredicate:predicate]];
    //刷新数据源
    [_tableView reloadData];
    
    
}

#pragma mark - 自定义协议方法


#pragma mark-交互时间


#pragma mark- 自定义方法


#pragma mark - getter&& setter
-(UITableView *)tableView
{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)-64) style:UITableViewStylePlain];
        
        _tableView.delegate = self;
        
        _tableView.dataSource =self;
        
    }
    
    
    return _tableView;
}
-(UISearchController *)searchController
{
    
    if (!_searchController) {
        
        _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
        //设置刷新者
        _searchController.searchResultsUpdater = self;
        //关闭透视效果
        _searchController.dimsBackgroundDuringPresentation = NO;
    }
    
    return _searchController;
    
}


@end
